import axios from 'axios'
import { message as Message } from 'antd';

const request = axios.create({
    baseURL: 'http://localhost:8888',
    header: {
      post: {
        'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
      },
      get: {
        'Content-Type': 'application/json;charset=utf-8'
      },
      timeout: 3000,
      withCredentials: true
    }
})

// axios 请求拦截器
request.interceptors.request.use(config => {
  const token = sessionStorage.getItem('token')
  config.headers = {
    ...config.headers,
    token
  }
  return config
},
 error => { // 错误处理
    return Promise.reject(error)
} )

// axios 请求响应拦截
request.interceptors.response.use(response=> {
   return response.data
}, error => {
    let message
    if (error && error.response) {
        switch (error.response.status) {
          case 400:
            message = "错误请求"
            break
          case 401:
            message = "未授权，请重新登录！"
            break
          case 403:
            message = "拒绝访问"
            break
          case 404:
            message = "请求错误,未找到该资源！"
            break
          case 405:
            message = "请求方法未允许"
            break
          case 408:
            message = "请求超时"
            break
          case 500:
            message = "服务器端出错"
            break
          case 501:
            message = "网络未实现"
            break
          case 502:
            message = "网络错误"
            break
          case 503:
            message = "服务不可用"
            break
          case 504:
            message = "网络超时"
            break
          case 505:
            message = "http版本不支持该请求"
            break
          default:
            message = `连接错误${error.response.status}`
        }
      } else {
        message = "连接到服务器失败"
      }
      Message.error(message)
      return Promise.reject(error)
})
const get = (url, params) => {
  return new Promise((resolve, reject) => {
    request.get(url, {params}).then((res) => resolve(res)).catch((error) => reject(error))
  })
}
const post = (url, params) => {
  return new Promise((resolve, reject) => {
    request.post(url, params).then((res) => resolve(res)).catch((error) => reject(error))
  })
}
const del = (url, params) => {
  return new Promise((resolve, reject) => {
    request.delete(url, params).then((res) => resolve(res)).catch((error) => reject(error))
  })
}
const put = (url, params) => {
  return new Promise((resolve, reject) => {
    request.put(url, params).then((res) => resolve(res)).catch((error) => reject(error))
  })
}

// get 方式请求
const service = {
  get,post,del,put
}

export default service
